<?php
namespace App\HttpController\Pudu;

use App\Common\Controller\Rest;

class ShopEmoney extends Rest
{
    public $modelName = 'ShopEmoney';   // model 类名称

    public function POSTIndex()
    {
        $userInfo = $this->model('Member') -> where(['id' => $this->param['userId']])->where(['roleId' => 2]) -> find(); // 确保申请电子币的是店铺
        $this->abort($userInfo, ['msg' => '只有店铺才能申请电子币!']);
        $this->param['username'] = $userInfo['username'];

        $res = $this->model()->createData($this->param, true);
        $this->result($res, ['msg' => self::$model->getError()]);
    }

    public function PUTIndex()
    {
        // TODO 电子币审核通过 需要生成记录
        if($this->param['status'] == 2) {
            // TODO 读取电子币额度
            $emoneyInfo = $this->model()->get($this->param['Id']);
            $Member = $this->model('Member');
            $userInfo = $Member ->where(['id' => $emoneyInfo['userId']])->find();
            $data = [
                'userId' => $userInfo['id'],
                'username' => $userInfo['username'],
                'change' => $emoneyInfo['much'],
                'remain' => $userInfo['emoney'] + $emoneyInfo['much'],
                'type' => 3,
                'remark' => '电子币充值',
            ];
            $Member->startTrans();
            try{
                $this->model('MemberRecord')->insert($data);
                $Member->where(['id' => $emoneyInfo['userId']])->setInc('emoney', $emoneyInfo['much']);
                $Member->commit();
            }catch(\Exception $e){
                $Member->rollback();
                $this->error(['msg' => $e->getMessage()]);
            }
        }
        $res = $this->model()->updateDataById($this->param, $this->param['Id']);
        $this->result($res, ['msg' => self::$model->getError()]);
    }

}
